﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using System.Xml;
using Microsoft.Xna.Framework.Content.Pipeline;

namespace CrateManiaPipeline
{
    /// <summary>
    /// Represents a tiled map.
    /// </summary>
    public class TileMapContent
    {
        /// <summary>
        /// Map width (in tiles unit)
        /// </summary>
        public int Width;

        /// <summary>
        /// Map height (in tiles height)
        /// </summary>
        public int Height;

        /// <summary>
        /// Tileset (by reference)
        /// </summary>
        public ExternalReference<TilesetContent> TilesetRef;

        /// <summary>
        /// Embedded tileset
        /// </summary>
        public TilesetContent Tileset;

        /// <summary>
        /// Map layers
        /// </summary>
        public List<TileMapLayerContent> Layers = new List<TileMapLayerContent>();

        public TileMapContent(XmlNode mapNode, ContentImporterContext context)
        {
            Width = int.Parse(mapNode.Attributes["width"].InnerText);
            Height = int.Parse(mapNode.Attributes["height"].InnerText);
            XmlNode tileset = mapNode["tileset"];
            XmlNode tilesetSourceAttr = tileset.Attributes["source"];
            if ( tilesetSourceAttr != null )
            {
                TilesetRef = new ExternalReference<TilesetContent>(tilesetSourceAttr.InnerText);
            }
            else
            {
                Tileset = new TilesetContent(tileset, context);
            }
            foreach (XmlNode layer in mapNode.SelectNodes(".//layer"))
            {
                Layers.Add(new TileMapLayerContent(layer, context));
            }
        }
    }
}
